/**
 * Created by WT-SUN on 2017/4/27.
 */
var lastIndex='lastIndex';
$(function () {
    $('#monitorDataTb').datagrid({
        view: detailview,
        rownumbers: true,//显示行号
        striped: true,
        fit: true,
        sortOrder: true,
        fitColumns: true,
        pagination: true,
        toolbar: '#toolbar',
        url: ROOT_PATH + '/occupationalHealth/monitor/monitorTable.shtml',
        queryParams:{
            sort:'addTime',
            order:'asc',
            isOverproof:'0'
        },
        detailFormatter:function(index,row){
            return '<div class="taskddv" style="padding:5px"></div>';
        },
        onCollapseRow:function(index,row){
            var ddv = $('#monitorDataTb').datagrid('getRowDetail', index).find('table.tbddv');
            ddv.datagrid('clearSelections');
        },
        onExpandRow: function(index,row){
            $('.taskddv').html('');
            if (lastIndex!='lastIndex'&&lastIndex!=index){
                $('#monitorDataTb').datagrid('collapseRow',lastIndex);
                $('.taskddv').empty();
            }
            var htmlTb='<table id="taskDivTb" class="tbddv"></table>';
            $('.taskddv').append(htmlTb);
            var ddv = $('#monitorDataTb').datagrid('getRowDetail', index).find('table.tbddv');
            ddv.datagrid({
                url: ROOT_PATH + '/task/selectByTaskId.shtml',
                queryParams: {
                    taskId: row.id,
                },
                fitColumns: true,
                singleSelect: true,
                rownumbers: true,
                loadMsg: '',
                height: 'auto',
                columns: [[
                    {
                        field: 'id',
                        checkbox: true
                    },
                    {
                        field: 'taskId', hidden:true, title: '业务Id', hidden:true,width: 20
                    },
                   /* {field: 'aa', title: '撤销', width: 50, sortable: true,formatter: function (value, row, index) {
                        return "<a href='javascript:void(0)' style='color:#0b6bc2;'  onclick='removeTask(\""+row.id+"\");'>撤销</a>";
                    }},*/
                    {field: 'taskName', title: '任务名称', width: 120},
                    {field: 'taskDescribe', title: '任务描述', width: 80},
                    {field: 'receiveUserName', title: '接收人', width: 100},
                    {field: 'jsDeptName', title: '接收单位', width: 100},
                    {field: 'requireTime', title: '要求完成日期', width: 100},
                    {field: 'acceptUserName', title: '验收人', width: 100},
                    {field: 'ysDeptName', title: '验收单位', width: 100},
                    {field: 'addTime', title: '下发时间', width: 100},
                    {field: 'state', title: '状态', width: 100,formatter: function (value, row, index) {
                        return typeof (row.state)=='undefined'?'<span class="color-important text-white" style="padding: 3px;border-radius:5px;">未下发</span>':(row.state=='1'?'<span class="color-info text-white" style="padding: 3px;border-radius:5px;">整改中</span>':'<span class="color-success text-white" style="padding: 3px;border-radius:5px;">已验收</span>');
                    }},
                ]],
                onLoadSuccess: function () {
                    lastIndex=index;
                    $('#monitorDataTb').datagrid('fixDetailRowHeight',index);
                }
            });
            $('#monitorDataTb').datagrid('fixDetailRowHeight',index);
        },
        columns: [[
            {
                field: 'id',
                checkbox: true
            },
            {field: 'monitorPoint', title: '监测点名称', width: 200, sortable: true,formatter: function (value, row, index) {
                return "<a href='javascript:void(0)' class='easyui-linkbutton text-primary' plain='true'  onclick='infoPData(\""+row.id+"\");'>"+row.monitorPoint+"</a>";
            }},
            {field: 'companyName', title: '单位名称', width: 100},
            {field: 'factorName', title: '监测项目', width: 100},
            {field: 'monitorResult', title: '监测结果', width: 100},
            {field: 'state', title: '状态', width: 100,formatter: function (value, row, index) {
                return typeof (row.state)=='undefined'?'<span class="color-important text-white" style="padding: 3px;border-radius:5px;">未下发</span>':(row.state=='1'?'<span class="color-info text-white" style="padding: 3px;border-radius:5px;">整改中</span>':'<span class="color-success text-white" style="padding: 3px;border-radius:5px;">已验收</span>');
            }},
            {field: 'cbNum', title: '超标倍数', width: 100},
            {field: 'cxNum', title: '超限倍数', width: 100},
            {field: 'mac', title: 'MAC', width: 100},
            {field: 'pctwa', title: 'PC-TWA', width: 100},
            {field: 'pcstel', title: 'PC-STEL', width: 100},
            /*{field: 'maxNum', title: '最大值', width: 100},
            {field: 'minNum', title: '最小值', width: 100},*/
            {field: 'isOverproof', title: '是否超标', width: 100,formatter: function (value, row, index) {
                return row.isOverproof == '1' ? '<span class="color-success text-white" style="padding: 3px;border-radius:5px;">否</span>' : '<span class="color-important text-white" style="padding: 3px;border-radius:5px;">是</span>';
            }},
            {field: 'deptName', title: '登记部门', width: 100},
            {field: 'addTime', title: '登记时间', width: 100}
        ]]
    });

    $('#btn_tmonitor_delete').on('click',function () {
        removeTask();
    });
    $('#btn_tmonitor_edit').on('click',function () {
        editmonitor();
    });
    var stateData=[{id:'',text:'请选择'},{id:'2',text:'未下发'},{id:'0',text:'已整改'},{id:'1',text:'整改中'}];
     $("#state").combobox({
     data: stateData,
     valueField: 'id',
     textField: 'text',
     editable: false,
     panelHeight: '150',
     selectOnNavigation:true
     });
    /**
     * 高级查询
     */
    $('#btn_advanced_search').on("click", function () {
        $('#queryForm2').toggle();
        $('#monitorDataTb').datagrid('resize');
    });
    $('#btn_clear').on("click", function () {
        $('#queryForm1').form('reset');
        $('#queryForm2').form('reset');
    });
    $('#btn_tmonitor_query').on('click',function () {
        reLoadData(lastIndex);
    });
    /**
     * 绑定监测单位选择事件
     */
    $("#monitorCompanyId").textbox({
        iconWidth: 20,
        icons: [{
            iconCls: 'icon-add',
            handler: function(e){
                openSerViceTb();
            }
        },{
            iconCls: 'icon-remove',
            handler: function(e){
                $(e.data.target).textbox('clear');
                $("#monitorCompanyId").val('');
            }
        }]
    });
    /**
     * 绑定人员选择事件
     */
    $("#searchAddUser").textbox({
        iconWidth: 20,
        icons: [{
            iconCls: 'icon-add',
            handler: function(e){
                add_userId_func();
            }
        },{
            iconCls: 'icon-remove',
            handler: function(e){
                $(e.data.target).textbox('clear');

            }
        }]
    });
    queryDepartmentTree();
});
function queryDepartmentTree(){
    $.ajax({
        url:ROOT_PATH + '/permission/department/getDepartmentTree.shtml',//提交地址
        data:{parentId : 0},//将表单数据序列化
        type:"POST",
        dataType:"json",
        success:function(result){
            //deptCom('searchDept',result);
            deptCom('searchAddDept',result);
        }
    });
}
function deptCom(id,result) {
    var deptId='#'+id;
    $(deptId).combotree(
        {
            data:result,
            require:true,
            prompt:'请选择',
            loadFilter:function(data){
                var newData = new Array();
                newData.push({id:"",text:'请选择'});
                newData.push(data[0]);
                return newData;
            }
        }
    );
}
var add_userId_func = function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0',
        callBack:function(data){
            getSelectedUser(data);
        }
    });
};
/**
 * 人员信息选择
 */
var getSelectedUser = function (data) {
    $("#searchAddUser").textbox('setValue', data[0].id).textbox('setText', data[0].realName);
};
function openSerViceTb() {
    WindowManager.openLayer({
        type: 2,
        title: '选择服务机构',
        area: ['850px', '70%'],
        content: ROOT_PATH + '/occupationalHealth/hseServiceOrg/orgTb.shtml',
        callBack:function(data){
            getSelectedOrg(data);
        }
    });
}
function getSelectedOrg(data) {
    $("#monitorCompanyId").textbox('setValue', data[0].id).textbox('setText', data[0].serviceName);
}
/**
 * 重新加载表格
 */
function reLoadData() {
    lastIndex='lastIndex';
    $('#monitorDataTb').datagrid('clearSelections');
    var queryParams1 = $('#queryForm1').serializeJson();
    var queryParams2 = $('#queryForm2').serializeJson();
    var queryParams = $.extend(queryParams1,queryParams2);
    queryParams["sort"] = 'addTime';
    queryParams["order"] = 'desc';
    queryParams["isOverproof"] = '0';
    $('#monitorDataTb').datagrid('options').queryParams = queryParams;
    $("#monitorDataTb").datagrid('reload', ROOT_PATH + '/occupationalHealth/monitor/monitorTable.shtml');
}
/**
 * 打开弹框
 * @param title
 * @param content
 */
function openLayers(title, content) {
    parent.layer.open({
        type: 2,
        resize: false,
        title: title,
        area: ['1150px', '85%'],
        content: content
    });
}
/**
 * 编辑
 */
function editmonitor() {
    var rows = $('#monitorDataTb').datagrid('getSelections');
    if (rows.length == 0) {
        layer.alert("请选择数据！");
        return;
    }

    var objTask={};//参数对象
    var taskArr=[];//任务数据数组
    for (var i=0;i<rows.length;i++){
        if( typeof (rows[i].state)=='undefined'){
            var obj={
                taskId:rows[i].id,//业务Id
                taskName:rows[i].monitorPoint+','+rows[i].factorName+'超标整改',//任务名称
                taskSource:'监测点超标整改'//来源模块
            };
            taskArr.push(obj);
        }
    }
    objTask.task=taskArr;//参数 对象中的键值可以不是task 但只有一个
    WindowManager.openLayer({//任务窗口
        type: 2,
        title: '批量任务下发',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/task/addTask.shtml',
        data:objTask,//参数
        callBack:function(data){//窗口关闭后的回调函数 data=true
            if (data){
                reLoadData();//重新加载表格
            }
        }
    });
}
function infoPData(id) {
    var title = '监测数据详情';
    var content = ROOT_PATH + '/occupationalHealth/monitor/info.shtml?resourceId=' + $.getQueryParam('resourceId')+'&id=' + id+'&type=info';
    parent.layer.open({
        type: 2,
        resize: false,
        title: title,
        area: ['1150px', '70%'],
        content: content
    });
}
/**
 * 撤销任务
 */
function removeTask() {
    if (lastIndex!='lastIndex'){
        var ddv = $('#monitorDataTb').datagrid('getRowDetail', lastIndex).find('table.tbddv');
        var rows = ddv.datagrid('getSelections');
        if(rows.length==0){
            layer.alert("请选择监测数据下的任务！");
            return;
        }else {
            if(rows[0].state=='0'){
                layer.alert("该任务已验收！");
                return;
            }
            var id=rows[0].id;
            layer.confirm('是否确定撤销当前任务？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                $.ajax({
                    type: 'post',
                    url: ROOT_PATH + '/task/deleteById.shtml',
                    data: {id: id},
                    dataType: "json",
                    success: function (result) {
                        if (result.success) {
                            $('#monitorDataTb').datagrid('clearSelections');
                            reLoadData();
                            layer.msg('撤销成功', {
                                icon: 1,
                                time: 1000
                            });
                        }
                        else {
                            layer.msg('撤销失败', {
                                icon: 2,
                                time: 1000
                            });
                        }
                    }
                });
            });
        }
    }else {
        layer.alert("请选择监测数据下的任务！");
        return;
    }
}

